package gui;

/*
 * Esse arquivo é parte do Software new Recicle
 * 
 * Copyright (C) 2011-$AnoCorrente$ Eduardo Moreira Barbosa
 * Copyright (C) 2011-$AnoCorrente$ João dos Santos Gonçalves
 * Copyright (C) 2011-$AnoCorrente$ Lucas Ximenes da Fonseca
 * 
 * new Recicle é um Software Livre: Você pode redistribuí-lo e/ou modificá-lo
 * de acordo com os termos da Licença Pública Geral GNU (GNU General Public License)
 * conforme publicada pela Free Software Foundation (FSF). Essa permissão é atribuída
 * na versão 3 da Licença, ou (na sua opinião) qualquer versão.
 * 
 * Você deve ter recebido uma cópia da Licença Pública Geral GNU junto com este programa,
 * se não, escreva para a Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301  USA
 * 
 * Se você tiver alguma dúvida e/ou quiser dar suporte ao desenvolvimento, favor entrar em
 * contato nos e-mails <barbosa.edrd@gmail.com>, <john.jsg@hotmail.com>, <lxf.lucas@gmail.com>.
 */

import bd.*;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import outros.Cpf;
import rh.Associado;

public class CadastrarAssociado extends javax.swing.JDialog {

    protected static CadastrarAssociado CADASTRAASSOCIADO;
    private static boolean isEdicao = false;
    private static String selecionado;
    
    public CadastrarAssociado(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        defineIconesFrame(); // Icone da JFrame
        
        String cancelName = "cancel";
        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName); 
    }
    
    public void setIsEdicao(boolean is) {
        isEdicao = is;
    }
    
    public void setSelecionado(String selecionado) {
        CadastrarAssociado.selecionado = selecionado;
    }
    
    private void cAssociado() {
        BancoAssociado bancoAssociado = new BancoAssociado();

        BancoDeDados bancoDeDados = new BancoDeDados();
        bancoDeDados.conectarBanco();

        if (nomeText.getText().length() > 3) {
            
            if (senhaText.getText().equals(senhaRText.getText())) {
                
                if ((cpfText.getText().endsWith(" "))
                        || (Cpf.calculaCpf(cpfText.getText()))) {
                    
                    String sex = sexoText.getText().toUpperCase();
                    if (sex.equals("M") || sex.equals("F")) {
                        
                        if (EscolheImagem.validacao() == true) {
                            
                            Associado.getAssociado().setNome(nomeText.getText());
                            Associado.getAssociado().setSenha(senhaText.getText());
                            Associado.getAssociado().setSexo(sexoText.getText());
                            Associado.getAssociado().setCpf(cpfText.getText());
                            Associado.getAssociado().setImagem(imagemPath.getText());
                            bancoAssociado.cadastrar();

                            /*
                             * Atualiza os botões.
                             */
                            NewRecicle.atualizaBotoes();
                            
                            this.dispose();
                        } else {
                            avisos.setText("Aviso!: Imagem inválida! Escolha um arquivo: JPG ou PNG...");
                        }
                    } else {
                        avisos.setText("Aviso!: Sexo deve ser M ou F...");
                    }
                } else {
                    avisos.setText("Aviso!: CPF inválido! Confira e tente novamente...");
                }
                
            } else {
                avisos.setText("Aviso!: Senhas diferentes! Por favor, tente novamente...");
            }
        } else {
            avisos.setText("Aviso!: Nome muito curto ou em branco! Deve ter pelo menos 4 letras...");
        }
    }
    
    private void eAssociado(String selecionado) {
        
        BancoDeDados bancoDeDados = new BancoDeDados();
        bancoDeDados.conectarBanco();
        
        Associado associado = new Associado();
              
        BancoAssociado bancoAssociado = new BancoAssociado();

        if ( senhaText.getText().equals(senhaRText.getText()) ) {
            if ( Cpf.calculaCpf( cpfText.getText() ) ) {
                String sex = sexoText.getText().toUpperCase();
                
                if ( sex.equals("M") || sex.equals("F")) {
                    if (EscolheImagem.validacao() == true) {
                        
                        associado.setNome( nomeText.getText() );
                        associado.setSenha( senhaText.getText() );
                        associado.setCpf( cpfText.getText() );
                        associado.setSexo( sexoText.getText() );
                        associado.setImagem( imagemPath.getText() );
                        
                        /*
                         * Alteração no banco.
                         */
                        bancoAssociado.alterar(associado, selecionado);
                        
                        /*
                         * Atualizar os botões
                         */
                        NewRecicle.atualizaBotoes();
                        /* 
                         * Volta ao padrão da variavel
                         */
                        isEdicao = false;
                        
                        this.dispose();
                        
                    } else {
                        avisos.setText("Aviso!: Imagem inválida! Escolha um arquivo: JPG ou PNG...");
                    }
                } else {
                    avisos.setText("Aviso!: Sexo deve ser M ou F...");
                }
            } else {
                avisos.setText("Aviso!: CPF inválido! Confira e tente novamente...");
            }

        } else {
            avisos.setText("Aviso!: Senhas diferentes! Por favor, tente novamente...");
        }
    }


    public void editandoAssociado(String nome, String senha, String cpf, String sexo) {
        nomeText.setText(nome);
        senhaText.setText(senha);
        senhaRText.setText(senha);
        cpfText.setText(cpf);
        sexoText.setText(sexo);
    }
    
    private void defineIconesFrame(){
        try {
            //Setando o Icone do Frame Principal
            this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/imagens/ervilha/Logo.png")));
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        imagemPath = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        avisos = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        senhaText = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        nomeText = new javax.swing.JTextField();
        sexoText = new javax.swing.JFormattedTextField();
        senhaRText = new javax.swing.JPasswordField();
        okButton = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        cpfText = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrado de Associado");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel6.setText("* Campo obrigatório!");

        imagemPath.setEditable(false);
        imagemPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                imagemPathActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Sexo: *");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setText("Senha: *");

        avisos.setFont(new java.awt.Font("Tahoma", 1, 12));
        avisos.setForeground(new java.awt.Color(255, 0, 0));
        avisos.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        avisos.setText("#");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel1.setText("Nome: *");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel4.setText("CPF:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 13));
        jLabel5.setText("Redigite a senha: *");

        senhaText.setFont(new java.awt.Font("Tahoma", 0, 14));

        jButton1.setText("Escolher imagem");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        nomeText.setFont(new java.awt.Font("Tahoma", 0, 14));
        nomeText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nomeTextActionPerformed(evt);
            }
        });

        try {
            sexoText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("*")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        sexoText.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        senhaRText.setFont(new java.awt.Font("Tahoma", 0, 14));

        okButton.setFont(new java.awt.Font("Tahoma", 1, 18));
        okButton.setText("Confirmar");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 13));
        jLabel7.setText("Imagem: *");

        try {
            cpfText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(cpfText, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(36, 36, 36)
                                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(sexoText, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addComponent(senhaText, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 108, Short.MAX_VALUE)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                                .addComponent(jLabel5)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(senhaRText, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                                .addComponent(jLabel7)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(imagemPath, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(jButton1))))
                                    .addComponent(nomeText, javax.swing.GroupLayout.DEFAULT_SIZE, 796, Short.MAX_VALUE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 291, Short.MAX_VALUE)
                                .addComponent(avisos, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(313, 313, 313)
                        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nomeText, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(senhaRText, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5)
                    .addComponent(senhaText, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(cpfText, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(imagemPath, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel7)
                        .addComponent(jLabel2)
                        .addComponent(sexoText, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(44, 44, 44)
                .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel6)
                    .addComponent(avisos, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        getRootPane().setDefaultButton(okButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        if (isEdicao == false) {
            cAssociado();
        } else if (isEdicao){
            eAssociado(selecionado);
        }
    }//GEN-LAST:event_okButtonActionPerformed
    
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
       
    }//GEN-LAST:event_closeDialog

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        imagemPath.setText(EscolheImagem.imagemPath());
    }//GEN-LAST:event_jButton1ActionPerformed

    private void imagemPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imagemPathActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_imagemPathActionPerformed

    private void nomeTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nomeTextActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_nomeTextActionPerformed

    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastrarAssociado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastrarAssociado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastrarAssociado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastrarAssociado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                CADASTRAASSOCIADO = new CadastrarAssociado(new javax.swing.JFrame(), true);
                CADASTRAASSOCIADO.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                CADASTRAASSOCIADO.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel avisos;
    private javax.swing.JFormattedTextField cpfText;
    private javax.swing.JTextField imagemPath;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField nomeText;
    private javax.swing.JButton okButton;
    private javax.swing.JPasswordField senhaRText;
    private javax.swing.JPasswordField senhaText;
    private javax.swing.JFormattedTextField sexoText;
    // End of variables declaration//GEN-END:variables
}